from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from datetime import datetime

from app.api import deps
from app.schemas import attraction_ticket as schemas
from app.database.models.erp import AttractionTicket, PackageOrder
from app.database.models.base import User

router = APIRouter()

@router.get("/", response_model=List[schemas.AttractionTicket])
def list_attraction_tickets(
    db: Session = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    attraction_name: Optional[str] = None,
    ticket_status: Optional[str] = None,
    package_order_id: Optional[int] = None,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取景点门票订单列表"""
    try:
        query = db.query(AttractionTicket)
        
        # 根据用户角色和工作区过滤
        if current_user.role == "agent":
            # agent只能查看自己工作区的订单
            query = query.filter(AttractionTicket.work_area_id == current_user.workarea_id)
        elif current_user.role != "admin":
            # 非管理员且非agent的用户无权限查看
            raise HTTPException(
                status_code=403,
                detail="Not enough permissions to view attraction tickets"
            )
        
        # 添加过滤条件
        if attraction_name:
            query = query.filter(AttractionTicket.attraction_name.like(f"%{attraction_name}%"))
        if ticket_status:
            query = query.filter(AttractionTicket.ticket_status == ticket_status)
            
        # 按打包订单ID过滤
        if package_order_id is not None:
            if package_order_id <= 0:
                query = query.filter(AttractionTicket.package_order_id == -1)
            else:
                query = query.filter(AttractionTicket.package_order_id == package_order_id)

        # 添加排序和分页，使用参观日期降序排序
        query = query.order_by(AttractionTicket.visit_date.desc())
        tickets = query.offset(skip).limit(limit).all()
        
        return tickets
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Error fetching attraction tickets: {str(e)}"
        )

@router.post("/", response_model=schemas.AttractionTicket)
def create_attraction_ticket(
    *,
    db: Session = Depends(deps.get_db),
    ticket_in: schemas.AttractionTicketCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新的景点门票订单"""
    try:
        # 使用当前用户的工作区ID
        ticket_data = ticket_in.dict()
        ticket_data["work_area_id"] = current_user.workarea_id

        # 设置默认值
        if not ticket_data.get("package_order_id") or ticket_data["package_order_id"] <= 0:
            ticket_data["package_order_id"] = -1
            ticket_data["package_order_title"] = None
        else:
            # 如果关联了打包订单，查询订单标题
            package_order = db.query(PackageOrder).filter(
                PackageOrder.ID == ticket_data["package_order_id"]
            ).first()
            if package_order:
                ticket_data["package_order_title"] = package_order.title

        ticket = AttractionTicket(**ticket_data)
        db.add(ticket)
        db.commit()
        db.refresh(ticket)
        return ticket
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/{ticket_id}", response_model=schemas.AttractionTicket)
def get_attraction_ticket(
    ticket_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取特定景点门票订单详情"""
    try:
        ticket = db.query(AttractionTicket).filter(AttractionTicket.ID == ticket_id).first()
        if not ticket:
            raise HTTPException(status_code=404, detail="Attraction ticket not found")

        # 如果关联了package_order，检查权限
        if ticket.package_order_id:
            order = db.query(PackageOrder).filter(
                PackageOrder.ID == ticket.package_order_id
            ).first()
            if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
                raise HTTPException(status_code=403, detail="Not enough permissions")

        return ticket
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/{ticket_id}", response_model=schemas.AttractionTicket)
def update_attraction_ticket(
    *,
    db: Session = Depends(deps.get_db),
    ticket_id: int,
    ticket_in: schemas.AttractionTicketUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新景点门票订单信息"""
    try:
        ticket = db.query(AttractionTicket).filter(AttractionTicket.ID == ticket_id).first()
        if not ticket:
            raise HTTPException(status_code=404, detail="Attraction ticket not found")

        # 检查权限
        if current_user.role != "admin" and ticket.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 更新门票信息
        update_data = ticket_in.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(ticket, field, value)

        db.add(ticket)
        db.commit()
        db.refresh(ticket)
        return ticket
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{ticket_id}", response_model=schemas.AttractionTicket)
def delete_attraction_ticket(
    *,
    db: Session = Depends(deps.get_db),
    ticket_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除景点门票订单"""
    try:
        ticket = db.query(AttractionTicket).filter(AttractionTicket.ID == ticket_id).first()
        if not ticket:
            raise HTTPException(status_code=404, detail="Attraction ticket not found")

        # 检查权限
        if current_user.role != "admin" and ticket.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 如果有关联的package_order，检查是否允许删除
        if ticket.package_order_id and ticket.package_order_id > 0:
            package_order = db.query(PackageOrder).filter(
                PackageOrder.ID == ticket.package_order_id
            ).first()
            if package_order and package_order.status not in ["draft", "cancelled"]:
                raise HTTPException(
                    status_code=400,
                    detail="Cannot delete ticket from a confirmed or completed package order"
                )

        db.delete(ticket)
        db.commit()
        return ticket
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e)) 